#include <iostream>
#include <cstring>
using namespace std;

#include "UserManager.h"

DatabaseManager::DatabaseManager() : db(nullptr) {}

DatabaseManager::~DatabaseManager() {
    disconnect();
}

bool DatabaseManager::connect() {
    if (sqlite3_open(DB_NAME, &db)) {  // 使用宏定义的数据库名
        cerr << "Can't open database: " << sqlite3_errmsg(db) << endl;
        return false;
    }
    return true;
}

bool DatabaseManager::disconnect() {
    if (db) {
        sqlite3_close(db);
        db = nullptr;
    }
    return true;
}

bool DatabaseManager::executeQuery(const string& query) {
    char* errMsg = nullptr;
    if (sqlite3_exec(db, query.c_str(), nullptr, nullptr, &errMsg) != SQLITE_OK) {
        cerr << "SQL error: " << errMsg << endl;
        sqlite3_free(errMsg);
        return false;
    }
    return true;
}

vector<string> DatabaseManager::fetchResults(const string& query) {
    sqlite3_stmt* stmt;
    vector<string> results;
    if (sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const char* text = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
            if (text) {
                results.push_back(text);
            }
        }
        sqlite3_finalize(stmt);
    } else {
        cerr << "Failed to fetch results: " << sqlite3_errmsg(db) << endl;
    }
    return results;
}

